<?php namespace Home\Controller; 

use Hdphp\Controller\Controller;

class OrderController extends CommonController{
//	1.商品表
	private $goodsModel;
//	2.地址表
	private $addrModel;
//	3.订单表
	private $ordersModel;
//	4.订单列表
	private $orderlistModel;
//	5.货品表
	private $glistModel;
	public function __init(){
		parent::__init();
		$this->goodsModel = new \Common\Model\Goods;
		$this->addrModel = new \Common\Model\Address;
		$this->ordersModel = new \Common\Model\Orders;
		$this->orderlistModel = new \Common\Model\OrderList;
		$this->glistModel = new \Common\Model\Glist;
	}
	
	public function index(){
//		1.生成订单表
		$oid = $this->ordersModel->store();//获得订单id
		if(!$oid) View::error($this->ordersModel->getError());
//		2.生成订单列表
		if(!$this->orderlistModel->store($oid)) View::error($this->orderlistModel->getError());
//		3.扣除库存
		$this->deduct();
//		4.删除购物车数据
		if(!Q('post.session_id')){//加判断区别购物车和直接购买
			foreach (Q('post.session_id') as $k => $v) {
				$data = array(
					'sid'=>$v,
					'num'=>0,
				);
				Cart::update($data);
			}
		}
		View::make();
	}
	
//	扣除库存函数
	public function deduct(){
		$data = Q('post.');
		foreach ($data['gid'] as $k => $v) {
			$glist = $this->glistModel->where("combine = '{$data['value'][$k]}' AND goods_gid = $v")->find();
			$inve = $glist['inventory'] - intval($data['num'][$k]);
			$this->glistModel->where("glid = {$glist['glid']}")->update(array('inventory'=>$inve));
			$oldinve = Db::table('goods')->where("gid = {$data['gid'][$k]}")->pluck('inventory');
			$nowinve = $oldinve-intval($data['num'][$k]);
			Db::table('goods')->where("gid = {$data['gid'][$k]}")->update(array('inventory'=>$nowinve));
		}
	}
	
	
	
	
	
	
	
	
	
	
}
